package main;

import java.io.IOException;

//Nikolas Wolfe
//2/20/09
//CIS 4930
//Candybox

// Driver class for the candy simulation

public class CandyDriver
{	
	public static void main(String args[]) 
	{
		int n; 
		int t;
		int s; 
		try {
			n = Integer.parseInt(args[0]); // number of Candy instances
			t = Integer.parseInt(args[1]); // number of CandySamplerThreads
			s = Integer.parseInt(args[2]); // number of seconds to run
		} catch (Exception e)
		{
			// Defaults
			n = 6;
			t = 6;
			s = 6;
		}
		
		CandyBox box = new CandyBox(n);
		Thread[] threads = new Thread[t];
		CandySamplerThread[] samplers = new CandySamplerThread[t];
		
		for(int i = 0; i < t; ++i)
		{
			samplers[i] = new CandySamplerThread(box);
			threads[i] = new Thread(samplers[i]);
		}
		System.out.println("CandyBox initialized with " + n + " candy pieces " +
				"and " + t + " candy nibbler(s)!");
		System.out.println("==============================================" +
				"==================\n");
		
		ThreadKiller tKiller = new ThreadKiller(threads, (s*1000));
		Thread killer = new Thread(tKiller);
		
		for(int i = 0; i < threads.length; ++i)
		{
			threads[i].start();
		}
		
		killer.start();
		try
		{
			killer.join();
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("\nTIMEOUT OCCURRED! "
				+ "\n\nCandyBox Status Report:\n");

		box.printStatus();
		System.out.println();
		for (int i = 0; i < samplers.length; ++i)
		{
			samplers[i].printStatus();
		}
	}
	
	private static class ThreadKiller implements Runnable
	{
		private Thread[] tList;
		private int time; 
		
		public ThreadKiller( Thread[] tList, int time )
		{
			this.tList = tList;
			this.time = time;
		}
		
		public void run()
		{
			try
			{
				Thread.sleep(time);
				for(int i = 0; i < tList.length; ++i)
				{
					tList[i].interrupt();
					tList[i].join();
				}
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}
